<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">

      <el-form-item label="类型" prop="stockBillType">
        <el-select v-model="query.stockBillType" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option label="入库" :value="1" />
          <el-option label="出库" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="query.storeId" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型">
        <el-select v-model="query.reBillType" placeholder="请选择">
          <el-option label="请选择" :value="-1" />
          <el-option
            v-for="item in msgTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="name">
        <el-input v-model="query.operator" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select
          v-model="dateType"
          style="width: 170px; margin-right: 2px;"
        >
          <el-option label="操作时间" value="createTime" />
          <el-option label="审核时间" value="enterDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="storeId">
        <el-select v-model="query.billStatus" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in billStatusMap"
            :key="item.key"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格" prop="storeId">
        <el-select v-model="query.specCode" placeholder="请选择">
          <el-option
            v-for="item in goodsSpecificationMap"
            :key="item.specCode"
            :label="item.specName"
            :value="item.specCode"
          />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <store-info ref="storeInfo" />
  </div>
</template>

<script>
  import { selectStockBillList, selectOrgSNNoAndReType, goodsSpecification, stockInBillInvalid, queryMap, stockInBillStockInBillInvalid } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import moment from 'dayjs'
  import StoreInfo from './components/StoreInfo'
  export default {
    name: 'inAndOutManage',
    components: {
      StoreInfo
    },
    data() {
      return {
        dateType: 'createTime',
        date: [moment().startOf('month'), moment().endOf('hour')],
        goodsSpecificationMap: [],
        storeMap: [],
        msgTypeMap: [], // 业务类型
        query: {
          storeId: 0,
          stockBillType: 0,
          operator: '',
          reBillType: -1,
          billStatus: 0,
          specCode: ''
        },
        billStatusMap: [
          { value: -1, desc: '作废', key: 'INVALID' },
          { value: 1, desc: '待确认', key: 'NOTCHECKED' },
          { value: 2, desc: '已确认', key: 'CHECKED' },
          { value: 3, desc: '已驳回', key: 'REJECT' }
        ],
        tableData: {
          total: 0,
          column: [
            {
              prop: 'stockCode',
              label: '单号',
              width: 270,
              render: (h, { row }) => <el-link onClick={() => this.stockCodeHandle(row)}>{row.stockCode}</el-link>
            },
            {
              prop: 'stockBillType',
              label: '类型',
              render: (h, { row }) => (
              <span>{row.stockBillType === 1 ? '入库' : ' 出库'}</span>
            )
            },
            {
              prop: 'reBillType',
              label: '业务类型',
              render: (h, { row }) => (
              <span>
                {row.reBillType &&
                  formatColumnMap(
                    this.msgTypeMap,
                    'value',
                    row.reBillType,
                    'desc'
                  )}
              </span>
            )
            },
            {
              prop: 'reBillCode',
              label: '关联调拨单号',
              render: (h, { row }) => <el-link onClick={() => this.stockCodeHandle(row)}>{row.reBillCode}</el-link>
            },
            {
              prop: 'storeName',
              label: '仓库'
            },
            {
              prop: 'operator',
              label: '操作人'
            },
            {
              prop: 'createTime',
              label: '操作时间',
              width: 160,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'modifyUser',
              label: '审核人'
            },
            {
              prop: 'enterDt',
              label: '审核时间',
              width: 160,
              render: (h, { row }) => <span>{ row.enterDt && parseTime(row.enterDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'billStatus',
              label: '状态',
              render: (h, { row }) => (
              <span>
                {row.billStatus &&
                  formatColumnMap(
                    this.billStatusMap,
                    'value',
                    row.billStatus,
                    'desc'
                  )}
              </span>
            )
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 180,
              render: (h, { row, $index }) => {
                return (
                <div>
                  { row.billStatus === 1 && <el-link size='mini' onClick={() => this.examineHandler(row)}>出入库审核</el-link>}
                  { row.billStatus === 1 && <el-link size='mini' onClick={() => this.delHandler(row)}>作废</el-link>}
                </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    async created() {
      await this.initStoreMap()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          params[this.dateType] = this.date[0]
          params[`${this.dateType}End`] = this.date[1]
        }
        if (!this.query.specCode) {
          params['specCode'] = ''
        }
        const res = await selectStockBillList(params)
        console.log('水水水水水水', res)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async initStoreMap() {
        selectOrgSNNoAndReType({
          reType: 4
        }).then(res => {
          this.storeMap = res.data
        })

        goodsSpecification({
          pageIndex: 1,
          pageSize: 10000
        }).then(res => {
          this.goodsSpecificationMap = res.data.rows
        })

        queryMap({
          enumName: 'StockFullReType'
        }).then(res => {
          const arr = [0, 3, 4]
          res.data.map(item => {
            if (!arr.includes(item.value)) {
              this.msgTypeMap.push(item)
            }
          })
        })
      },
      examineHandler(row) {
        console.log(row)
      },
      stockCodeHandle(row) {
        console.log('飒飒水水', row)
        this.$refs.storeInfo.open(row)
      },
      delHandler(row) {
        this.$confirm('确认作废吗？', '提示', {
          type: 'warning'
        }).then(async() => {
          // const loading = this.$message({
          //   message: '正在作废',
          //   duration: 0,
          //   iconClass: 'el-icon-loading'
          // })
          // stockInBillInvalid({ billCode: row.reBillCode }).then(() => {
          //   this.search()
          //   this.$notify({
          //     title: '提示',
          //     message: '作废成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // }).finally(() => {
          //   loading.close()
          // })
          if (row.stockBillType === 1) { // 入库
            const res = await stockInBillStockInBillInvalid({
              billCode: row.stockCode
            })
            console.log('res', res)
            if (res.status === 200) {
              this.$message({
                type: 'success',
                message: '作废成功!'
              })
              this.$refs.lbTable.fetch({ currentPage: 1 })
            }
          } else { // 出库
            const res = await stockInBillInvalid({
              billCode: row.stockCode
            })
            console.log('res', res)
            if (res.status === 200) {
              this.$message({
                type: 'success',
                message: '作废成功!'
              })
              this.$refs.lbTable.fetch({ currentPage: 1 })
            }
          }
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },

      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
